import React, { memo, useEffect, useState, useCallback } from "react";
import {
  Table,
  Popconfirm,
  Button,
  Form,
  Modal,
  Input,
  message,
  DatePicker,
  Pagination,
} from "antd";
import { Blogadminwrap } from "./style";
import Uploadyzh from "@/components/uploadyzh";
import request from "@/service/request";
import { UserOutlined } from "@ant-design/icons";
import qs from "qs";
export default memo(function Blogadmin() {
  //外层表格，外层表格
  const [tablewrap, setTablewrap] = useState([]);
  //方便搜索博客
  const [tablewrap1, setTablewrap1] = useState([]);
  //修改博客表单是否显示
  const [blogvis, setBlogvis] = useState(false);
  //修改评论的对话框是否显示
  const [pinvis, setPinvis] = useState(false);
  //用来初始化博客表单
  const [form1] = Form.useForm();
  //用来初始化评论表单
  const [form2] = Form.useForm();
  //博客封面
  const [imguser, setImguser] = useState("");
  //避免博客丢失的id
  const [bgid, setBgid] = useState();
  //避免评论id的丢失
  const [pinid, setPinid] = useState();
  //每一页的数量
  const [pagesize, setPagesize] = useState(5);
  //当前在第几页
  const [currentindex, setCurrentindex] = useState(0);
  useEffect(() => {
    request.get("travel/Blogcom").then((value) => {
      setTablewrap(value);
      setTablewrap1(value);
    });
  }, []);

  //修改博客的对话框
  const xiugaiblog = (text) => {
    setBgid(text.id);
    setBlogvis(true);
    setImguser(text.pic);
    form1.setFieldsValue(text);
  };
  //显示修改评论的对话框
  const xiugaipinlun = (text) => {
    setPinvis(true);
    form2.setFieldsValue(text);
    setPinid(text.id);
  };
  //删除博客
  const deleteblog = (id) => {
    request.get(`travel/handleblog?id=${id}`).then((res) => {
      message.success("删除博客成功");
      request.get("travel/Blogcom").then((value) => {
        setTablewrap(value);
        setTablewrap1(value);
      });
    });
  };
  //提交修改博客的表单
  const blogfinish = (value) => {
    value.id = bgid;
    value.pic = imguser;
    request.post("travel/handleblog", qs.stringify(value)).then((value) => {
      message.success("修改博客成功");
      setBlogvis(false);
      request.get("travel/Blogcom").then((value) => {
        setTablewrap(value);
        setTablewrap1(value);
      });
    });
  };
  //提交修改评论表单
  const pinfinish = (value) => {
    value.id = pinid;
    request.post("travel/handlecomment", qs.stringify(value)).then((value) => {
      message.success("修改评论成功");
      setPinvis(false);
      request.get("travel/Blogcom").then((value) => {
        setTablewrap(value);
        setTablewrap1(value);
      });
    });
  };
  //删除评论
  const deletepinlun = (text) => {
    request.get(`travel/handlecomment?id=${text.id}`).then(() => {
      message.success("删除评论成功");
      request.get("travel/Blogcom").then((value) => {
        setTablewrap(value);
        setTablewrap1(value);
      });
    });
  };
  //接收回传的图片
  const setimg = useCallback((img) => {
    setImguser(img);
  }, []);
  //博客表格
  const column1 = [
    {
      title: "封面",
      dataIndex: "pic",
      key: "pic",
      align: "center",
      width: 50,
      ellipsis: true,
      render: (record) => {
        return <img src={record} alt="" style={{ width: 40, height: 40 }} />;
      },
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      align: "center",
      width: 70,
      ellipsis: true,
    },
    {
      title: "发布内容",
      dataIndex: "summary",
      key: "summary",
      align: "center",
      width: 100,
      ellipsis: true,
    },
    {
      title: "发布日期",
      dataIndex: "releaseDate",
      key: "releaseDate",
      align: "center",
      width: 80,
      ellipsis: true,
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      align: "center",
      width: 90,
      ellipsis: true,
      render: (id, record) => (
        <div className="btwrap">
          <Button
            type="primary"
            shape="round"
            size={"middle"}
            onClick={(e) => xiugaiblog(record)}
          >
            修改
          </Button>
          <Popconfirm
            title="你确定删除此博客吗？"
            okText="确定"
            cancelText="取消"
            onConfirm={(e) => deleteblog(id)}
          >
            <Button type="primary" danger shape="round" size={"middle"}>
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  // 嵌套的评论表格
  const expandedRowRender = (record) => {
    const columns = [
      {
        title: "内容",
        dataIndex: "content",
        key: "content",
        align: "center",
        width: 100,
        ellipsis: true,
      },
      {
        title: "发表时间",
        dataIndex: "commentDate",
        key: "commentDate",
        align: "center",
        width: 100,
        ellipsis: true,
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        key: "caozuo",
        align: "center",
        width: 100,
        ellipsis: true,
        render: (id, record) => {
          return (
            <div className="btwrap">
              <Button
                type="primary"
                shape="round"
                size={"middle"}
                onClick={(e) => xiugaipinlun(record)}
              >
                修改
              </Button>
              <Popconfirm
                title="你确定删除此用户吗?"
                okText="确定"
                cancelText="取消"
                onConfirm={(e) => deletepinlun(record)}
              >
                <Button type="primary" danger shape="round" size={"middle"}>
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    return (
      <Table
        columns={columns}
        dataSource={record.coms}
        pagination={false}
        rowKey={(record) => record.id}
      />
    );
  };
  //搜索博客发生变化
  const searchchange = useCallback(
    (e) => {
      setTablewrap(
        tablewrap1.filter((item) => {
          return item.title.indexOf(e.target.value) !== -1;
        })
      );
    },
    [tablewrap1]
  );
  //时间过滤改变
  const handleSelectTime = useCallback(
    (value, dateString) => {
      if (dateString[0].length === 0) {
        setTablewrap(tablewrap1);
      } else {
        setTablewrap(
          tablewrap1.filter((item) => {
            return (
              item.releaseDate.slice(0, 10) >= dateString[0] &&
              item.releaseDate.slice(0, 10) <= dateString[1]
            );
          })
        );
      }
    },
    [tablewrap1]
  );
  const pagechange = useCallback((page, size) => {
    setPagesize(size);
    setCurrentindex((page - 1) * size);
  }, []);
  return (
    <Blogadminwrap>
      <div className="top">你当前的位置>博客管理</div>
      {/* 修改博客对话框 */}
      <Modal
        title="修改博客信息"
        visible={blogvis}
        onCancel={(e) => setBlogvis(false)}
        footer={[]}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={blogfinish}
          form={form1}
          autoComplete="off"
        >
          <Form.Item
            label="博客标题"
            name="title"
            rules={[{ required: true, message: "Please input your title!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="博客内容"
            name="summary"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="发表时间"
            name="releaseDate"
            rules={[
              { required: true, message: "Please input your releaseDate!" },
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="pic"
            label="封面"
            rules={[
              {
                required: true,
                message: "Please input Intro",
              },
            ]}
          >
            <div className="upload">
              <Uploadyzh setimg={setimg} imgurl={imguser}></Uploadyzh>
            </div>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              修改博客信息
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {/* 修改评论对话框 */}
      <Modal
        title="修改博客信息"
        visible={pinvis}
        onCancel={(e) => setPinvis(false)}
        footer={[]}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={pinfinish}
          form={form2}
          autoComplete="off"
        >
          <Form.Item
            label="评论内容"
            name="content"
            rules={[{ required: true, message: "请输入评论内容!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              修改博客内容
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <div className="searchwrap">
        {/* 过滤博客 */}
        <Input
          size="large"
          placeholder="输入你要搜索的博客标题"
          onChange={searchchange}
          prefix={<UserOutlined />}
        />
        {/* 时间筛选框 */}
        <Input.Group compact>
          <DatePicker.RangePicker
            onChange={handleSelectTime}
            style={{ width: "70%" }}
          />
        </Input.Group>
      </div>
      <Table
        columns={column1}
        dataSource={tablewrap.slice(currentindex, currentindex + pagesize)}
        rowKey={(record) => record.id}
        expandedRowRender={(record) => expandedRowRender(record)}
        scroll={{ y: 400 }}
        pagination={false}
      />
      <div className="page">
        <Pagination
          pageSize={pagesize}
          total={tablewrap.length}
          onChange={pagechange}
          pageSizeOptions={[5, 8, 10]}
          showSizeChanger
        />
      </div>
    </Blogadminwrap>
  );
});
